package com.qingcheng.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.qingcheng.service.goods.SkuSearchService;
import com.qingcheng.utils.WebUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;


import java.util.Map;

@Controller
public class SearchController {
    @Reference(timeout = 1000000)
    private SkuSearchService skuSearchService;

    @GetMapping("/search")
    public String findSkuBySearch(Model model, @RequestParam Map<String,String> searchMap) throws Exception {
        //修改字符集
        searchMap= WebUtil.convertCharsetToUTF8(searchMap);

        //处理分页传入的参数
        if(searchMap.get("pageNo")==null || "".equals(searchMap.get("pageNo"))){
            searchMap.put("pageNo","1");
        }
        //将searchMap中的pageNo存入静态页面中
        int pageNo=Integer.parseInt(searchMap.get("pageNo"));
        model.addAttribute("pageNo",pageNo);

        //第一次访问，给排序默认值
        if(searchMap.get("sortName")==null && searchMap.get("sortOrder")==null){
            searchMap.put("sortOrder","DESC");
            searchMap.put("sortName","");
        }

        //获取对象map集合响应回前台
        Map resultMap = skuSearchService.findSkuBySearchMap(searchMap);

        //获取总页数
        int totalPages = (Integer) resultMap.get("totalPages");
        //判断起始页码和终止页码
        int startPage=0;
        int endPage=0;
        if(totalPages<=5){
            startPage=1;
            endPage=totalPages;
        }else{
            if((pageNo-2)<1){
                startPage=1;
            }else{
                startPage=pageNo-2;
            }
            endPage=startPage+4;
        }
        //防止start无限增长
        if(endPage>totalPages){
            endPage=totalPages;
            startPage=totalPages-4;

        }

        //将页码存入model中
        model.addAttribute("startPage",startPage);
        model.addAttribute("endPage",endPage);


        //响应url
        StringBuilder url=new StringBuilder("/search.do?name="+searchMap.get("name"));
        //url="/search.do?name='小米'"
        for(String key:searchMap.keySet()){
            //动态增加url
            if(!"name".equals(key) && !"pageNo".equals(key)){
                url.append("&"+key+"="+searchMap.get(key));
            }
        }
        model.addAttribute("url",url);

        //将传入的参数响应回浏览器
        model.addAttribute("searchMap",searchMap);

        //将数据封装进search集合中
        model.addAttribute("resultMap",resultMap);
        return "search";
    }

}
